<?php
/**********************************************
* 파일명: attach.php
* 설  명: 스킨첨부파일을 저장하는 php 파일입니다.
* 특  징: 스킨파일 업로드시 같은 이름의 파일을 덮어씁니다.
***********************************************/

define (UPLOAD_ORIGINAL,0);
define (UPLOAD_TIMESTAMP,1);
define (UPLOAD_UNIQID,2);

class AttachFile {

	var $path;
	var $ext;
	var $naming;
	var $exts	= "gif|jpg|jpeg|png|bmp";	//표시 할 이미지 확장자
	var $skinfiles ="xml|html|css|js";

	function AttachFile($naming=UPLOAD_ORIGINAL,$ext="") {
		if ($naming) $this->setNamingMethod($naming);
		if ($ext) $this->setSaveExt($ext);
	}

	function setSavePath($path) {
		$this->path = $path;
	}

	function setSaveExt($ext) {
		$this->ext = $ext;
	}

	function setNamingMethod($naming) {
		$this->naming = $naming;
	}

	function save() {
		$argv = func_get_args();
		$argc = func_num_args();

		if ($argc > 0) {
			foreach($argv as $item) {
				$UPLOAD_FILES[$i] = &$_FILES[$item];
			}
		} else {
			$UPLOADED_FILES = &$_FILES;
		}

		if (count($UPLOADED_FILES) <= 0) return;

		$ret = array();
		foreach ($UPLOADED_FILES as $file) {
			if (is_array($file['name'])) {

			} else {
				if ($file['size'] == 0) continue;

				if(!eregi("\.($exts)",$file['name']) && !eregi("\.($skinfiles)",$file['name'])) continue;

				$ext = AttachFile::extSplit($file['name'],$noext);
				if ($this->ext) $ext = $this->ext;
				if ($this->naming == UPLOAD_TIMESTAMP) {
					$noext = date("U");
				} elseif ($this->naming == UPLOAD_UNIQID) {
					srand((double)microtime()*1000000);
					$noext = md5(uniqid(rand(),1));
				}

				if($this->naming == UPLOAD_ORIGINAL){
					$savepath = $this->path."${noext}.${ext}";
				}else{
				$seq = 0;
				do {
					if ($seq > 0) {
						$savename = "${noext}_${seq}.${ext}";
					}else{
						$savename = "${noext}.${ext}";
					}
					$savepath = $this->path."/${savename}";
					$seq++;
				} while (is_file($savepath));
				$seq = 0;
				}

				if (is_uploaded_file($file['tmp_name'])) {
					//echo $savepath;
					move_uploaded_file($file['tmp_name'],$savepath);
					$ret[] = array(
						'filename' => $file['name'],
						'filetype' => $ext,
						'filesize' => filesize($savepath),
						'filepath' => $savepath
					);
				}
			}
		}
		return $ret;
	}

	function extSplit($fileName,&$noext) {
		$dot = strrpos($fileName,".");
		$noext = substr($fileName,0, $dot);
		$noext  = str_replace(" ","_",$noext);
		return ($ext = substr($fileName,$dot+1)) ? $ext : "noext";
	}
}
?>
